package com.example.springbootkafka.threadpool;


import com.example.springbootkafka.configration.ThreadPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration

/**
 * 因为springboot默认使用的是SimpleAsyncTaskExecutor，每次提交任务都创建线程，要小心在使用大任务的场景下创建大量线程导致OOM异常
 * 如果自己不想重新自定义线程池，可以通过实现实现AsyncConfigurer接口重写一下springboot默认的线程池
 */
public class SpringTaskExector implements AsyncConfigurer {
    @Autowired
    private ThreadPoolConfig threadPoolConfig;

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程池大小
        executor.setCorePoolSize(threadPoolConfig.getCorePoolSize());
        //最大线程数
        executor.setMaxPoolSize(threadPoolConfig.getMaxPoolSize());
        //队列容量
        executor.setQueueCapacity(threadPoolConfig.getQueueCapacity());
        //活跃时间
        executor.setKeepAliveSeconds(threadPoolConfig.getKeepAliveSecond());
        //线程名字前缀
        executor.setThreadNamePrefix("SpringExecutor-");

        // setRejectedExecutionHandler：当pool已经达到max size的时候，如何处理新任务
        // CallerRunsPolicy：不在新线程中执行任务，而是由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}
